/* eslint-disable no-param-reassign */
/* eslint-disable prefer-destructuring */
/* eslint-disable no-mixed-operators */
/* eslint-disable no-restricted-globals */
/* eslint-disable no-plusplus */
/* eslint-disable object-curly-newline */

import Base from 'widget-base';
import debounce from 'lodash.debounce';
import find from 'lodash.find';
import anime from 'animejs';
import Model from './model';
import mainTpl from './templates/ui.tpl';

export default Base.View.extend({
  initialize($el, data = {}) {
    this.model = new Model({
      fullPath: data.fullPath,
      widgetWidth: $el.width(),
      widgetHeight: $el.height(),
      gridWidth: data.gridWidth,
      gridHeight: data.gridHeight,
      presetShape: data.presetShape,
      isDrawCircle:data.presetShape.isShowLine, // 是否是画的圆形
      isShowCircle:data.presetShape.isShowCircle, // 是否显示圆心
      severalCopies:data.severalCopies, // 分成几份
      initPreset:data.presetShape, // 初始化预设
    });
   
    this.addClass('./resources/css/main.css');
    this.addClass('./resources/css/tooltik.css');
    this.$el.html(mainTpl(data));
    if (this.useExtension) {
      this.useExtension("statisticsViewer", {
        __statisticsRenderSrc: "chineseInput/statisticsViewer.js",
        __interactDataCollectType: "page",
      });
    }
    this.$workspace = this.$el.find('.workspace');
    this.$canvas = this.$workspace.find('canvas');
    this.isMousedownTriggered = false;
    this.$dummyLine = this.$workspace.find('.dummy-line');
    this.$shapeContainer = this.$workspace.find('.shape-container');
    setTimeout(() => {
      this.initCanvas();
    }, 500);
    window.MyWidget = this;
    console.log(this, data);
  },

  events: {
    'mousedown .workspace .tools .tool[data-tool="line"]': 'onPressDownLineTool',
    'touchstart .workspace .tools .tool[data-tool="line"]': 'onPressDownLineTool',
    'mousedown .workspace': 'onPressDownWorkspace',
    'touchstart .workspace': 'onPressDownWorkspace',
    'mousemove .workspace': 'onPressMoveWorkspace',
    'touchmove .workspace': 'onPressMoveWorkspace',
    'mouseup .workspace': 'onPressUpWorkspace',
    'touchend .workspace': 'onPressUpWorkspace',
    'mouseleave .workspace': 'onPressUpWorkspace',
    'touchleave .workspace': 'onPressUpWorkspace',
  },

  __supportInteract: true,

  initCanvas() {
      const gridWidth = this.model.get('gridWidth');
      const gridHeight = this.model.get('gridHeight');
      this.$canvas[0].width = this.model.get('widgetWidth');
      this.$canvas[0].height = this.model.get('widgetHeight');
      this.$canvas.css('background-size', `${gridWidth}px ${gridHeight}px`);
      this.canvasCtx = this.$canvas[0].getContext('2d');
      this.initLinesArr();
      this.renderCanvas();
      this.$workspace.find('.no-draw').css('display', 'block');
  },
  findPointAtPos(pos) {
    const presetShape = this.model.get('presetShape').points;
    const tolerance = 10;
    if (!presetShape) return null;
    for (let i = presetShape.length - 1; i >= 0; i--) {
      const point = presetShape[i];
      if (Math.abs(point[0] - pos[0]) < tolerance && Math.abs(point[1] - pos[1]) < tolerance) {
        return { pointIndex: i };
      }
    }
    return null;
  },
  submit() {
    const result = {
      action: 'submitResult',
      data: {
        presetShape: this.model.get('presetShape'),
  
        operations: this.model.get('operations'),
        widgetId: this.itemId,
        widgetType: 'cutShape',
      },
      time: Date.now(),
    }
    if (typeof this.sendInteractData === 'function') {
      this.sendInteractData(result);
    }
  },

  onPressDownLineTool(evt) {
    evt.preventDefault();
    evt.stopPropagation();
    if(this.model.get('splitLines').length <1)
    this.isCreatingSplitLine = true;
    this.widgetRect = this.$el[0].getBoundingClientRect();
    if(this.model.get('initPreset').points.length >2) {
      this.showPresetShapeMiddlePoints()
    }
   
  },


/**
 * 获取形状框的对称点集合。
 * @param {Object} shapeBox - 表示形状框的对象，应包含x, y, w, h四个属性，分别代表左上角x坐标、左上角y坐标、宽度和高度。
 * @returns {Array} 返回一个包含四个对称点坐标的数组，每个点是一个包含x和y坐标的数组。
 */
getSymmetricPoints(shapeBox) {
  let symmetricPoints = []; // 初始化存储对称点的数组
  // 计算并添加水平对称点
  let xLeftPoint = [shapeBox.x, shapeBox.y + shapeBox.h / 2];
  let xRightPoint = [shapeBox.x + shapeBox.w, shapeBox.y + shapeBox.h / 2];
  symmetricPoints.push(xLeftPoint);
  symmetricPoints.push(xRightPoint);
  // 计算并添加垂直对称点
  let yTopPoint = [shapeBox.x + shapeBox.w / 2, shapeBox.y];
  let yBottomPoint = [shapeBox.x + shapeBox.w / 2, shapeBox.y + shapeBox.h];
  symmetricPoints.push(yTopPoint);
  symmetricPoints.push(yBottomPoint);
  return symmetricPoints; // 返回计算得到的对称点数组
},
/**
 * 反射点关于线
 * 此函数计算并返回一个点关于一条线的反射点。线由两个点组成，点用二维数组表示。
 * @param {Array} point 一个包含两个数字的数组，代表待反射的点的坐标 [x, y]。
 * @param {Array} line 一个包含两个点的数组，每个点也是一个包含两个数字的数组，代表线的起点和终点坐标 [[x1, y1], [x2, y2]]。
 * @return {Array} 返回一个包含两个数字的数组，代表反射点的坐标 [x, y]。
 */
reflectPointAboutLine(point, line) {
  // 计算线的斜率
  const dx = line[1][0] - line[0][0];
  const dy = line[1][1] - line[0][1];
  // 计算点到线的投影因子
  const t = ((point[0] - line[0][0]) * dx + (point[1] - line[0][1]) * dy) / (dx * dx + dy * dy);
  // 计算反射点的坐标
  const reflectedPoint = [
    2 * (line[0][0] + t * dx) - point[0],
    2 * (line[0][1] + t * dy) - point[1]
  ];
  return reflectedPoint;
},
  onPressDownWorkspace(evt) {
    evt.preventDefault();
    evt.stopPropagation();
    const clientX = evt.type === 'touchstart' ? evt.originalEvent.touches[0].clientX : evt.clientX;
    const clientY = evt.type === 'touchstart' ? evt.originalEvent.touches[0].clientY : evt.clientY;
      this.widgetRect = this.$el[0].getBoundingClientRect();
      const pos = [clientX - this.widgetRect.left, clientY - this.widgetRect.top];
      const linePoint = this.model.findLinePointAtPos(pos);
      if (linePoint) {
        this.mousedownLinePoint = linePoint;
        this.mousePos = pos;
      } else if (this.model.get('isSplitted')) {
        // 裁切后的多边形可以移动和旋转
        const shape = this.model.findShapeAtPos(pos);
        if (shape) {
          this.updateShapeContainer(shape);
          const shapeBox = this.model.getShapeBoundingBox(shape);
          shape.symmetricPoints = this.getSymmetricPoints(shapeBox);
          this.mousedownShape = shape;
          this.selectedShape = shape;
        } else {
          this.$shapeContainer.css('display', 'none');
          this.selectedShape = null;
        }
      }
      this.mousedownTime = Date.now();
  },

  onPressMoveWorkspace(evt) {
    evt.preventDefault();
    evt.stopPropagation();
    const clientX = evt.type === 'touchstart' ? evt.originalEvent.touches[0].clientX : evt.clientX;
    const clientY = evt.type === 'touchstart' ? evt.originalEvent.touches[0].clientY : evt.clientY;
    if (!this.widgetRect) return;
    const pos = [clientX - this.widgetRect.left, clientY - this.widgetRect.top];
    if (this.isCreatingSplitLine) {
      this.$dummyLine.css('left', `${pos[0]}px`).css('top', `${pos[1]}px`).css('display', 'block');
      this.mousePos = pos;
    } else if (this.mousedownLinePoint) {
      if (this.mousePos) {
        const deltaPos = [pos[0] - this.mousePos[0], pos[1] - this.mousePos[1]];
        const splitLines = this.model.get('splitLines');
        const point = splitLines[this.mousedownLinePoint.lineIndex].points[this.mousedownLinePoint.pointIndex];
        point[0] += deltaPos[0];
        point[1] += deltaPos[1];
        this.renderCanvas();
      }
      this.mousePos = pos;
    } 
  },

  onPressUpWorkspace() {
    // 添加切割线
    if (this.isCreatingSplitLine && this.mousePos) {
      this.model.addSplitLine(this.mousePos);
      this.renderCanvas();
    }
    // 移动切割线
    if (this.mousedownLinePoint && this.mousePos) {
      const splitLines = this.model.get('splitLines');
      const point = splitLines[this.mousedownLinePoint.lineIndex].points[this.mousedownLinePoint.pointIndex];
      this.model.get('operations').push({
        type: 'moveSplitLineEndPoint',
        data: {
          lineIndex: this.mousedownLinePoint.lineIndex,
          pointIndex: this.mousedownLinePoint.pointIndex,
          point: JSON.parse(JSON.stringify(point)),
        },
      });
    }
    this.isCreatingSplitLine = false;
    this.$dummyLine.css('display', 'none');
    this.mousePos = null;
    this.mousedownLinePoint = null;
    this.mousedownShape = null;
  },

  snapShape(shape, distance = 4) {
    const points = shape.transformedPoints || shape.points;
    let otherShapePoints = [];
    this.model.get('shapes').forEach((otherShape) => {
      if (otherShape !== shape) {
        otherShapePoints = otherShapePoints.concat(otherShape.transformedPoints || otherShape.points);
      }
    });
    // 吸附其它形状的顶点
    for (let i = 0; i < points.length; i++) {
      if (this.isPointInsideCanvas(points[i])) {
        for (let j = 0; j < otherShapePoints.length; j++) {
          if (this.model.calcDistance(points[i], otherShapePoints[j]) < distance) {
            return [otherShapePoints[j][0] - points[i][0], otherShapePoints[j][1] - points[i][1]];
          }
        }
      }
    }
    // 吸附网格点
    const gridWidth = this.model.get('gridWidth');
    const gridHeight = this.model.get('gridHeight');
    for (let i = 0; i < points.length; i++) {
      if (this.isPointInsideCanvas(points[i])) {
        const gridPoint = [
          Math.round(points[i][0] / gridWidth) * gridWidth,
          Math.round(points[i][1] / gridHeight) * gridHeight,
        ];
        if (this.model.calcDistance(points[i], gridPoint) < distance) {
          return [gridPoint[0] - points[i][0], gridPoint[1] - points[i][1]];
        }
      }
    }
    return null;
  },

  isPointInsideCanvas(point) {
    return point[0] >= 0 && point[1] >= 0 &&
      point[0] <= this.model.get('widgetWidth') && point[1] <= this.model.get('widgetHeight');
  },

  updateShapeContainer(shape) {
    const shapeBox = this.model.getShapeBox(shape);
    this.$shapeContainer.css('top', `${shapeBox.y}px`).css('left', `${shapeBox.x}px`)
      .css('width', `${shapeBox.w}px`).css('height', `${shapeBox.h}px`)
      .css('transform', `rotate(${shape.rotation || 0}deg)`)
      .css('display', 'block');
  },
  setDashLine() {
    const presetShape = this.model.get('presetShape');
    const allLines = this.generateLines(presetShape.points);
    this.splitShapeDashLinesArr = [];
    let color = '#d91616';
    allLines.forEach((line, i) => {
      let obj = {
        index: i,
        color,
        line,
        text: '',
        isDash: true
      }
      this.splitShapeDashLinesArr.push(obj);
      this.drawColorLine(line[0], line[1], color, 'dashLine');
    });
    if (!this.isHasDashLine) {
      this.splitShapeLinesArr.push(this.splitShapeDashLinesArr);
      this.isHasDashLine = true;
    }
  },
  /**
   * 交互接口 分割
   * @returns 
   */
  split() {
    const splitLines = this.model.get('splitLines');
    if (!splitLines.length) return;
    const presetShape = this.model.get('presetShape');
    if (!presetShape || !presetShape.points ) return;
    if(presetShape.points.length >=3) {
      let shapes = [presetShape];
      splitLines.forEach((line) => {
        let newShapes = [];
        shapes.forEach((shape) => {
          const splittedShapes = this.model.splitShape(shape.points, line.points);
          newShapes = newShapes.concat(splittedShapes);
        });
        shapes = newShapes;
      });
      this.model.set('isSplitted', true);
      this.model.set('shapes', [shapes[0]]);
      this.model.set('presetShape', shapes[0]);
      if(this.model.get('initPreset').points.length >2) {
        this.showPresetShapeMiddlePoints()
      }
      // this.model.set('splitLines', []);
      this.initSplitLinesArr(shapes);
      this.setfoldAnimation(shapes[1].points);    // 设置旋转的动画
      anime({
        targets: this.$flipShapeImg[0],
        rotateX: 180, // 沿X轴翻折180度以实现翻折动画
        easing: 'linear',
        complete: () => {
          this.$shapeContainer.hide();
        },
      });
  
      const data = {
        left: shapes[0],
        right: shapes[1],
        splitLines: JSON.parse(JSON.stringify(splitLines[0])),
      }
      const allShapes = this.model.get('allShapes');
      allShapes.push(data)
      this.model.set('allShapes', allShapes);
    }else  {
    console.log('presetShape.points.length', presetShape.points.length);
      const centerCircle = presetShape.points[0]
      const radius  = this.calculateRadius(presetShape.points);
      let shapes = [{
        centerCircle,
        radius,
        startAngle:0,
        endAngle:2*Math.PI
      }];
      console.log(JSON.stringify(shapes));
      console.log(JSON.stringify(splitLines));
      // splitCircleShape(shapes,splitLines)
    }
   
  },
  calculateRadius (points){
    var dx = points[1][0] - points[0][0];
    var dy = points[1][1] - points[0][1];
    return Math.sqrt(dx * dx + dy * dy);
  },
  /**
   * 展开图形
   */
  expandGraphic(){
    if(initPreset.points.length>=4) { // 矩形
      const initPreset = this.model.get("initPreset")
      const initWidth = this.calcateWidthAndHeight(initPreset.points).width
      const initHeight = this.calcateWidthAndHeight(initPreset.points).height
       const presetShape = this.model.get("presetShape")
       const presetShapetWidth = this.calcateWidthAndHeight(presetShape.points).width
       const presetShapeHeight = this.calcateWidthAndHeight(presetShape.points).height
       const widthNumber = Math.round(initWidth/presetShapetWidth)
       const heightNumber = Math.round(initHeight/presetShapeHeight)
       this.canvasCtx.clearRect(0, 0, this.$canvas[0].width, this.$canvas[0].height);
        this.drawRectWithLines(initPreset.points, widthNumber-1, heightNumber-1)
    }

   
 
  },
  drawRectWithLines(vertices, widthLines, heightLines) {
    // 提取矩形的四个顶点坐标
    var xValues = vertices.map(vertex => vertex[0]);
    var yValues = vertices.map(vertex => vertex[1]);
    
    // 计算矩形的宽度和高度
    var width = Math.max(...xValues) - Math.min(...xValues);
    var height = Math.max(...yValues) - Math.min(...yValues);
    
    // 计算水平线的间距和垂直线的间距
    var widthSpacing = width / (widthLines + 1);
    var heightSpacing = height / (heightLines + 1);
    
    // 绘制矩形
   
    this.canvasCtx.beginPath();
    this.canvasCtx.moveTo(vertices[0][0], vertices[0][1]);
    for (var i = 1; i < 4; i++) {
        this.canvasCtx.lineTo(vertices[i][0], vertices[i][1]);
    }
    this.canvasCtx.lineTo(vertices[0][0], vertices[0][1]);
    this.canvasCtx.strokeStyle = "#000";
    this.canvasCtx.stroke();
    
    // 绘制水平线
    this.canvasCtx.setLineDash([5, 5]); // 设置虚线样式
    this.canvasCtx.strokeStyle = "red";
    for (var i = 1; i <= heightLines; i++) {
        this.canvasCtx.beginPath();
        this.canvasCtx.moveTo(vertices[0][0], vertices[0][1] + i * heightSpacing);
        this.canvasCtx.lineTo(vertices[1][0], vertices[1][1] + i * heightSpacing);
        this.canvasCtx.stroke();
    }
    
    // 绘制垂直线
    this.canvasCtx.strokeStyle = "red";
    for (var i = 1; i <= widthLines; i++) {
        this.canvasCtx.beginPath();
        this.canvasCtx.moveTo(vertices[0][0] + i * widthSpacing, vertices[0][1]);
        this.canvasCtx.lineTo(vertices[3][0] + i * widthSpacing, vertices[3][1]);
        this.canvasCtx.stroke();
    }
},

  calcateWidthAndHeight(points) {
  var topLeft = points[0];
  var topRight = points[1];
  var bottomLeft = points[3];
  var width = topRight[0] - topLeft[0];
  var height = bottomLeft[1] - topLeft[1];
  return {width,height}
  },
  setfoldAnimation(points){
    const lastPoint = points[points.length - 1];
    const vAxis = [lastPoint[0] - points[0][0], lastPoint[1] - points[0][1]];
    /**
     * Math.atan2(y, x) 函数接受两个参数 y 和 x，
     * 分别表示点的纵坐标和横坐标。它返回的是点 (x, y) 相对于原点的极坐标角度，
     */
    const angle = Math.atan2(vAxis[1], vAxis[0]) * 180 / Math.PI;
    // 旋转图形至翻折轴为水平的位置，这样后续的翻折动画只要rotateX就可以了
    // 旋转中心为翻折轴的一个端点
    points = points.map((p, index) => {
      if (index === 0) return [...p];
      return this.model.rotatePoint(p, points[0], -angle);
    });
    const minX = Math.min(...points.map(p => p[0]));
    const minY = Math.min(...points.map(p => p[1]));
    const padding = 20;
    points = points.map(p => [p[0] - minX + padding, p[1] - minY + padding]);
    const maxX = Math.max(...points.map(p => p[0])) + padding;
    const maxY = Math.max(...points.map(p => p[1])) + padding;
    this.snapshotCanvas = document.createElement('canvas');
    this.snapshotCanvasCtx = this.snapshotCanvas.getContext('2d');
    this.snapshotCanvas.width = maxX;
    this.snapshotCanvas.height = maxY;
    this.snapshotCanvasCtx.lineWidth = 2;
    this.snapshotCanvasCtx.strokeStyle = '#ff0000';
    this.snapshotCanvasCtx.beginPath();
    this.snapshotCanvasCtx.moveTo(points[0][0], points[0][1]);
    for (let i = 1; i < points.length; i++) {
      this.snapshotCanvasCtx.lineTo(points[i][0], points[i][1]);
    }
    this.snapshotCanvasCtx.stroke();
    this.$flipShapeImg = this.$workspace.find('.flip-shape');
    this.$flipShapeImg[0].src = this.snapshotCanvas.toDataURL();
    // 翻折动画由图片的父元素和图片共同实现
    this.$shapeContainer.css('width', `${maxX}px`).css('height', `${maxY}px`);
    this.$shapeContainer.css('top', `${minY - padding}px`).css('left', `${minX - padding}px`);
    this.$shapeContainer.css('display', 'block');
    // 设置 transform-origin 为与上面旋转图形时的旋转中心一致的位置
    this.$shapeContainer.css('transform-origin', `${points[0][0]}px ${points[0][1]}px`);
    // 由于图形被旋转过，所以此处将父元素旋转相反的角度将其位置还原至初始位置
    this.$shapeContainer.css('transform', `rotateZ(${angle}deg)`);
    this.$flipShapeImg.css('transform-origin', `${points[0][0]}px ${points[0][1]}px`);
    this.$flipShapeImg.css('transform', 'rotateX(0deg)');
  },
  /**
   * 交互接口 设置填充颜色
   * @param {*} style 
   */
  setFillStyle(style) {
    if (style.brushColor) {
      console.log(style);
      this.model.set('FillColor', style.brushColor);
    }
  },
 
  renderCanvas() {
    this.$canvas[0].width = this.model.get('widgetWidth');
    const presetShape = this.model.get('presetShape');
    if(this.model.get('initPreset').points.length >2) {
      if (this.model.get('isSplitted')) {
        this.model.get('shapes').forEach((shape, index) => this.renderShape(shape, false, index));
        // this.setDashLine();
      } else {
        this.renderShape(presetShape);
      }
      const presetShapeMiddlePoints = this.model.get('presetShapeMiddlePoints');
      if (presetShapeMiddlePoints) {
        presetShapeMiddlePoints.forEach(point => this.renderMiddlePoint(point));
      }
      const splitLines = this.model.get('splitLines');
      if (splitLines.length) {
        for (let i = 0; i < splitLines.length; i++) {
          const line = splitLines[i];
          this.renderSegment(line);
        }
      }
    }else {
      this.renderShape(presetShape);
      console.log(11);
      const splitLines = this.model.get('splitLines');
      if (splitLines.length) {
        for (let i = 0; i < splitLines.length; i++) {
          const line = splitLines[i];
          this.renderSegment(line);
        }
      }
    }
    
  },

  renderShape(shape, fillShape = false, index) {
    if (!shape) return;
    const isDrawCircle = shape.isDrawCircle;
    const isShowCircle = shape.isShowCircle;
    const points = shape.transformedPoints || shape.points;
    // if (!points || points.length < 3) return;
    if (!points) return;
    this.canvasCtx.lineWidth = 2;
    this.canvasCtx.strokeStyle = '#000';
    const shapePath = new Path2D();
    if(isDrawCircle) {
      const radius =Math.sqrt(Math.pow((points[1][0] - points[0][0]), 2) + Math.pow((points[1][1] - points[0][1]), 2));
      this.canvasCtx.arc(points[0][0], points[0][1], radius, 0, 2 * Math.PI,false);
      this.canvasCtx.stroke();
      this.canvasCtx.closePath();
      if(isShowCircle) {
        this.renderMiddlePoint(points[0]) // 显示圆心
      }
    }else {
      shapePath.moveTo(points[0][0], points[0][1]);
      for (let i = 1; i < points.length; i++) {
        const point = points[i];
        shapePath.lineTo(point[0], point[1]);
      }
      shapePath.closePath();
      this.canvasCtx.stroke(shapePath);
      if (this.model.get('shapes').length === 0) {
        this.presetShapeLinesArr.forEach((item) => {
          this.drawColorLine(item.line[0], item.line[1], item.color);
          if (item.text) this.drawText(item.line[0], item.text);
        });
      } else {
        const allLines = this.generateLines(points);
        // this.splitShapeLinesArr[index].forEach((item, i) => {
        //   this.drawColorLine(allLines[i][0], allLines[i][1], item.color);
        //   if (item.text) this.drawText(allLines[i][0], item.text);
        // });
      }
    }
   
    
   
  },

  renderSegment(segment) {
    const pointRaidus = 10;
    this.canvasCtx.lineWidth = 2;
    this.canvasCtx.strokeStyle = '#ff2a51';
    this.canvasCtx.beginPath();
    this.canvasCtx.moveTo(segment.points[0][0], segment.points[0][1]);
    this.canvasCtx.lineTo(segment.points[1][0], segment.points[1][1]);
    this.canvasCtx.stroke();
    this.canvasCtx.fillStyle = '#007936';
    this.canvasCtx.beginPath();
    this.canvasCtx.ellipse(segment.points[0][0], segment.points[0][1], pointRaidus, pointRaidus, 0, 0, 2 * Math.PI);
    this.canvasCtx.fill();
    this.canvasCtx.beginPath();
    this.canvasCtx.ellipse(segment.points[1][0], segment.points[1][1], pointRaidus, pointRaidus, 0, 0, 2 * Math.PI);
    this.canvasCtx.fill();
    this.canvasCtx.beginPath();
    this.canvasCtx.ellipse(segment.points[0][0], segment.points[0][1], pointRaidus, pointRaidus, 0, 0, 2 * Math.PI);
    this.canvasCtx.stroke();
    this.canvasCtx.beginPath();
    this.canvasCtx.ellipse(segment.points[1][0], segment.points[1][1], pointRaidus, pointRaidus, 0, 0, 2 * Math.PI);
    this.canvasCtx.stroke();
  },

  renderMiddlePoint(point) {
    const pointRaidus = 6;
    this.canvasCtx.lineWidth = 2;
    this.canvasCtx.strokeStyle = '#ff2a51';
    this.canvasCtx.fillStyle = '#007936';
    this.canvasCtx.beginPath();
    this.canvasCtx.ellipse(point[0], point[1], pointRaidus, pointRaidus, 0, 0, 2 * Math.PI);
    this.canvasCtx.fill();
    this.canvasCtx.stroke();
  },

  reset() {
    this.model.reset();
    this.renderCanvas();
    this.isHasDashLine = false;
    this.$workspace.find('.tools').css('display', 'block');
    this.$shapeContainer.css('display', 'none');
    this.initCanvas()
  },

  showPresetShapeMiddlePoints() {
  console.log(1);
    const middlePoints = [];
    const presetShape = this.model.get('presetShape');
    for (let i = 0; i < presetShape.points.length; i++) {
      const p = presetShape.points[i];
      const pNext = presetShape.points[(i + 1) % presetShape.points.length];
      middlePoints.push([(p[0] + pNext[0]) / 2, (p[1] + pNext[1]) / 2]);
    }
    this.model.set('presetShapeMiddlePoints', middlePoints);
    console.log(middlePoints);
    this.renderCanvas();
  },

  hidePresetShapeMiddlePoints() {
    this.model.set('presetShapeMiddlePoints', null);
    this.model.get('operations').push({
      type: 'hidePresetShapeMiddlePoints',
    });
    this.renderCanvas();
  },

  initLinesArr() {
    this.presetShapeLinesArr = [];
    const presetShape = this.model.get('presetShape');
    // if (!presetShape || !presetShape.points || presetShape.points.length < 3) return;
    if (!presetShape || !presetShape.points ) return;
    const allLines = this.generateLines(presetShape.points);
    allLines.forEach((line, i) => {
      const color = '#000';
      this.presetShapeLinesArr.push({
        index: i,
        color,
        line,
      });
      this.drawColorLine(line[0], line[1], color);
    });
  },

  initSplitLinesArr(shapes) {
    this.splitShapeLinesArr = [];
    shapes.forEach((shape) => {
      const colorLineArr = [];
      const points = shape.points;
      const allLines = this.generateLines(points);
   
      allLines.forEach((line, i) => {
        let color = '#000';
        let text = '';
        this.presetShapeLinesArr.forEach((item) => {
          const itemLinePoint = item.line[0];
          const equalSlope = this.slopeDifference(line, item.line);
          const isInside = this.areEndpointsInside(line, item.line);
          if (equalSlope && isInside) color = item.color;
          if (itemLinePoint.toString() === line[0].toString()) text = item.text;
        });
        colorLineArr.push({
          index: i,
          color,
          line,
          text,
        });
      });
      this.splitShapeLinesArr.push(colorLineArr);
    });
  },
  drawColorLine(startPoint, endPoint, color, isDash) {
    this.canvasCtx.beginPath();
    this.canvasCtx.moveTo(startPoint[0], startPoint[1]);
    this.canvasCtx.lineTo(endPoint[0], endPoint[1]);
    if (isDash && isDash === 'dashLine') this.canvasCtx.setLineDash([5, 5]);
    this.canvasCtx.strokeStyle = color;
    this.canvasCtx.stroke();
  },

 

  generateLines(points) {
    const lines = [];
    if (!points || points.length < 2) return lines;
    for (let i = 0; i < points.length - 1; i++) {
      lines.push([points[i], points[i + 1]]);
    }
    lines.push([points[points.length - 1], points[0]]);
    return lines;
  },

  findNearestLine(point, lines) {
    const [x, y] = point;
    let minDistance = Number.MAX_VALUE;
    let nearestLine = null;
    const threshold = 10;
    let nearestLineIndex = -1;
    for (let i = 0; i < lines.length; i++) {
      const line = lines[i];
      const [start, end] = line;
      const distance = this.pointToLineDistance(x, y, start[0], start[1], end[0], end[1]);
      if (distance < minDistance && distance < threshold) {
        minDistance = distance;
        nearestLine = line;
        nearestLineIndex = i;
      }
    }
    return nearestLine ? {
      line: nearestLine,
      index: nearestLineIndex,
    } : null;
  },

  pointToLineDistance(x, y, x1, y1, x2, y2) {
    const A = x - x1;
    const B = y - y1;
    const C = x2 - x1;
    const D = y2 - y1;
    const dot = A * C + B * D;
    const lenSq = C * C + D * D;
    const param = dot / lenSq;
    let xx;
    let yy;
    if (param < 0 || (x1 === x2 && y1 === y2)) {
      xx = x1;
      yy = y1;
    } else if (param > 1) {
      xx = x2;
      yy = y2;
    } else {
      xx = x1 + param * C;
      yy = y1 + param * D;
    }
    const dx = x - xx;
    const dy = y - yy;
    return Math.sqrt(dx * dx + dy * dy);
  },

  slopeDifference(line1, line2) {
    // 判断斜率是否相等
    const slope1 = this.calculateSlope(line1[0], line1[1]);
    const slope2 = this.calculateSlope(line2[0], line2[1]);
    const slopeDifference = Math.abs(slope1 - slope2);
    const equalSlope = slopeDifference < 0.000001;
    return equalSlope;
  },

  calculateSlope(point1, point2) {
    return (point2[1] - point1[1]) / (point2[0] - point1[0]);
  },

  areEndpointsInside(line1, line2) {
    // 判断是否在线段内
    const x1Line1 = line1[0][0];
    const y1Line1 = line1[0][1];
    const x2Line1 = line1[1][0];
    const y2Line1 = line1[1][1];
    const x1Line2 = line2[0][0];
    const y1Line2 = line2[0][1];
    const x2Line2 = line2[1][0];
    const y2Line2 = line2[1][1];
    const isStartInside = x1Line1 >= Math.min(x1Line2, x2Line2) && x1Line1 <= Math.max(x1Line2, x2Line2) &&
      y1Line1 >= Math.min(y1Line2, y2Line2) && y1Line1 <= Math.max(y1Line2, y2Line2);
    const isEndInside = x2Line1 >= Math.min(x1Line2, x2Line2) && x2Line1 <= Math.max(x1Line2, x2Line2) &&
      y2Line1 >= Math.min(y1Line2, y2Line2) && y2Line1 <= Math.max(y1Line2, y2Line2);
    return isStartInside && isEndInside;
  },

  refreshUI(options) {
    console.log(options);
    if (options.presetShape) {
      this.model.set('presetShape', options.presetShape);
      this.initLinesArr();
      this.renderCanvas();
    }
    if (options.gridWidth || options.gridHeight) {
      if (options.gridWidth) this.model.set('gridWidth', options.gridWidth);
      if (options.gridHeight) this.model.set('gridHeight', options.gridHeight);
      const gridWidth = this.model.get('gridWidth');
      const gridHeight = this.model.get('gridHeight');
      this.$canvas.css('background-size', `${gridWidth}px ${gridHeight}px`);
    }
    if (options.width || options.height) {
      if (options.width) this.model.set('widgetWidth', options.width);
      if (options.height) this.model.set('widgetHeight', options.height);
      this.$canvas[0].width = this.model.get('widgetWidth');
      this.$canvas[0].height = this.model.get('widgetHeight');
      this.initLinesArr();
      this.renderCanvas();
    }
    
  },
});
